package cn.jekun.web.agent.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;









import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.D;
import cn.jekun.component.base.validator.annotation.Num;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.ErpOrderMessage;
import cn.jekun.component.core.bean.gen.ErpOrders;
import cn.jekun.component.core.bean.gen.ErpShop;
import cn.jekun.component.core.bean.gen.RsAgent;
import cn.jekun.component.core.service.gen.ErpOrderItemsService;
import cn.jekun.component.core.service.gen.ErpOrderLogService;
import cn.jekun.component.core.service.gen.ErpOrderMessageService;
import cn.jekun.component.core.service.gen.ErpOrdersService;
import cn.jekun.component.core.service.gen.ErpShopService;
import cn.jekun.component.shop.service.SendMessageService;
import cn.jekun.web.agent.bean.Order;

@Service(OrderService.BEAN_NAME)
public class OrderService extends AgentBaseService{
	public static final String BEAN_NAME = "cn.jekun.web.agent.service.OrderService";

	@Resource(name = cn.jekun.component.shop.service.OrderService.BEAN_NAME)
	cn.jekun.component.shop.service.OrderService orderService;

	@Override
	public String getNamespace() {
		return "ACTION_AGENT_ORDER";
	}
	@Resource(name=ErpOrdersService.BEAN_NAME)
	ErpOrdersService erpOrdersService;
	@Resource(name=ErpOrderItemsService.BEAN_NAME)
	ErpOrderItemsService erpOrderItemsService;
	@Resource(name=ErpOrderLogService.BEAN_NAME)
	ErpOrderLogService erpOrderLogService;
	
	@Resource(name = ErpOrderMessageService.BEAN_NAME)
	protected ErpOrderMessageService erpOrderMessageService;
	
	@Resource(name=SendMessageService.BEAN_NAME)
	SendMessageService sendMessageService;
	
	@Resource(name=ErpShopService.BEAN_NAME)
	ErpShopService erpShopService;
	/**
	 * 订单列表
	 * @param userId
	 * @param status
	 * @param page
	 * @return
	 */
	public List<Order> getMyOrders(@D String beginDate,
			   					   @D String endDate,
			   					   @Num(length=10,scale=2,message="订单开始金额非法") String beginAmt,
			   					   @Num(length=10,scale=2,message="订单结束金额非法") String endAmt,
			   					   @ErpOrders.AnnoPaymentId String paymentId,
			   					   @ErpOrders.AnnoOrderTypeId String erpOrderType,
			   					   @Num(length=10,message="订单开始数量非法")String beginnums,
			   					   @Num(length=10,message="订单开始数量非法") String endnums,
			   					   @ErpOrders.AnnoOrderStatusId String orderstatusId,
			   					   @ErpOrders.AnnoOrderId String orderId,
			   					   @RsAgent.AnnoAgentId String agentId,
			   					   @ErpOrders.AnnoOrderStatusId String payStatus, 
			   					   @ErpOrders.AnnoBusinessId String businessTypeId,
			   					   String userName,
			   					   @ErpShop.AnnoShopName String shopName,
			   						Page page) {

		try{
			
			Map map = new HashMap();
			map.put("beginAmt", beginAmt==null?"":beginAmt);
			map.put("endAmt", endAmt==null?"":endAmt);
			map.put("beginDate", beginDate==null?"":beginDate);
			map.put("endDate", endDate==null?"":endDate);
			map.put("beginnums", beginnums==null?"":beginnums);
			map.put("endnums", endnums==null?"":endnums);
			map.put("paymentId", paymentId==null?"":paymentId);
			map.put("erpOrderType", erpOrderType==null?"":erpOrderType);
			map.put("orderstatusId", orderstatusId==null?"":orderstatusId);
			map.put("orderId", orderId==null?"":orderId);
			map.put("userName", userName==null?"":userName);
			map.put("shopName", shopName==null?"":shopName);
			map.put("businessTypeId", businessTypeId==null?"":businessTypeId);
			map.put("payStatus", payStatus==null?"":payStatus);
			
			
			String SQL = this.getWhereSql(map);
			SqlUtis.prepareSql(map,SQL);
			
			map.put("agentId", agentId);
			SqlUtis.prepareSql(map,SQL);
			return this.list(getStatementName("selectAgentOrders"), map,page);

		}catch(BusinessException e){
			throw e;
		}catch(Exception e){
			e.printStackTrace();
		}

		return null;

	}
	
	public Double sumTotalAmount(@D String beginDate,
			   @D String endDate,
			   @Num(length=10,scale=2,message="订单开始金额非法") String beginAmt,
			   @Num(length=10,scale=2,message="订单结束金额非法") String endAmt,
			   @ErpOrders.AnnoPaymentId String paymentId,
			   @ErpOrders.AnnoOrderTypeId String erpOrderType,
			   @Num(length=10,message="订单开始数量非法")String beginnums,
			   @Num(length=10,message="订单开始数量非法") String endnums,
			   @ErpOrders.AnnoOrderStatusId String orderstatusId,
			   @ErpOrders.AnnoOrderId String orderId,
			   @RsAgent.AnnoAgentId String agentId,
			   @ErpOrders.AnnoOrderStatusId String payStatus, 
			   @ErpOrders.AnnoBusinessId String businessTypeId,
			   String userName,
			   @ErpShop.AnnoShopName String shopName
			   ){
		try{
			
			Map map = new HashMap();
			map.put("beginAmt", beginAmt==null?"":beginAmt);
			map.put("endAmt", endAmt==null?"":endAmt);
			map.put("beginDate", beginDate==null?"":beginDate);
			map.put("endDate", endDate==null?"":endDate);
			map.put("beginnums", beginnums==null?"":beginnums);
			map.put("endnums", endnums==null?"":endnums);
			map.put("paymentId", paymentId==null?"":paymentId);
			map.put("erpOrderType", erpOrderType==null?"":erpOrderType);
			map.put("orderstatusId", orderstatusId==null?"":orderstatusId);
			map.put("orderId", orderId==null?"":orderId);
			map.put("userName", userName==null?"":userName);
			map.put("shopName", shopName==null?"":shopName);
			map.put("businessTypeId", businessTypeId==null?"":businessTypeId);
			map.put("payStatus", payStatus==null?"":payStatus);
			
			
			String SQL = this.getWhereSql(map);
			SqlUtis.prepareSql(map,SQL);
			
			map.put("agentId", agentId);
			SqlUtis.prepareSql(map,SQL);
			return this.one(getStatementName("countAgentOrders"), map);
			
			
		}catch(BusinessException e){
			throw e;
		}catch(Exception e){
			e.printStackTrace();
		}

		return 0.0;
	}

	/**
	 * 订单查询条件
	 * @param map
	 * @return
	 */
	private String getWhereSql(Map map){
		String SQL = "";
		
		String beginAmt = map.get("beginAmt").toString();
		String endAmt = map.get("endAmt").toString();
		String beginDate = map.get("beginDate").toString();
		String endDate = map.get("endDate").toString();
		String beginnums = map.get("beginnums").toString();
		String endnums = map.get("endnums").toString();
		String paymentId = map.get("paymentId").toString();
		String erpOrderType = map.get("erpOrderType").toString();
		String orderstatusId = map.get("orderstatusId").toString();
		String orderId = map.get("orderId").toString();
		String userName = map.get("userName").toString();
		String shopName = map.get("shopName").toString();
		String businessTypeId = map.get("businessTypeId").toString();
		String payStatus = map.get("payStatus").toString();
		
		
		if(!"".equals(beginAmt) && "".equals(endAmt)){
			SQL +=" and a.total_amount>="+beginAmt; 
		}if("".equals(beginAmt) && !"".equals(endAmt)){
			SQL +=" and a.total_amount<="+endAmt; 
		}if(beginAmt!=null && endAmt!=null && !"".equals(beginAmt) 
				&& !"".equals(endAmt)){
			SQL +=" and a.total_amount>="+beginAmt+" and a.total_amount<="+endAmt+""; 
		}if("".equals(beginDate) && !"".equals(endDate)){
			SQL +=" and a.create_time"
					+ "<= to_date('"+beginDate.toString().trim()+" 23:59:59','yyyy/MM/dd hh24:mi:ss')";
		}if(!"".equals(beginDate) && "".equals(endDate)){
			SQL +=" and a.create_time"
					+ ">= to_date('"+beginDate.toString().trim()+"','yyyy/MM/dd hh24:mi:ss')";
		}if(!"".equals(beginDate) && beginDate!=null 
				&& !"".equals(endDate) && endDate!=null){
			SQL +=" and a.create_time >= to_date('"+beginDate.toString().trim()+"','yyyy/MM/dd hh24:mi:ss')"
					+ " and a.create_time <= to_date('"+endDate.toString().trim()+" 23:59:59','yyyy/MM/dd hh24:mi:ss')";
		}if(!"".equals(beginnums) && "".equals(endnums)){
			SQL +=" and a.nums>="+beginnums; 
		}if("".equals(beginnums) && !"".equals(endnums)){
			SQL +=" and a.nums<="+endnums; 
		}if(beginnums!=null && endnums!=null && !"".equals(beginnums) 
				&& !"".equals(endnums)){
			SQL +=" and a.nums>="+beginnums+" and a.nums<="+endnums+"";
		}
		if(paymentId!=null && paymentId.toString().length()>0){
			SQL +=" and a.payment_id = '"+paymentId.toString()+"'"; 
		}
		if(erpOrderType!=null && erpOrderType.toString().length()>0){
			SQL +=" and a.order_type_id = '"+erpOrderType.toString()+"'"; 
		}
		if(orderstatusId!=null && orderstatusId.toString().length()>0){
			SQL +=" and a.order_status_id = '"+orderstatusId.toString()+"'"; 
		}
		if(orderId!=null && orderId.toString().length()>0){
			SQL +=" and a.order_id like '%"+orderId.toString()+"%'"; 
		}
		if(userName!=null && userName.toString().length()>0){
			SQL +=" and u.user_name like '%"+userName+"%'"; 
		}
		if(shopName!=null && shopName.toString().length()>0){
			SQL +=" and p.shop_name like '%"+shopName+"%'"; 
		}
		if(businessTypeId!=null && businessTypeId.toString().length()>0){
			SQL +=" and bu.business_id = '"+businessTypeId+"'"; 
		}
		if(payStatus!=null && payStatus.toString().length()>0){
			
			if(payStatus.equals("1")){
				
				//已支付
				SQL +=" and a.pay_Time IS NOT NULL"; 
				
			}else if(payStatus.equals("2")){
				
				//未支付
				SQL +=" and a.pay_Time IS NULL"; 
			}
			
		}
		return SQL;
	}
	/**
	 * 订单详情
	 * @param orderId
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Order getOrder(@ErpOrders.AnnoOrderId String orderId) {
		try{
			Map queryMap = new HashMap();
			queryMap.put("orderId", orderId);
			//订单信息
			return this.one(getStatementName("selectAgentOrder"), queryMap);
			
		}catch(BusinessException e){
			throw e;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 订单商品详情
	 * @param orderId
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Order> getOrderGoods(@ErpOrders.AnnoOrderId String orderId) {
		try{
			Map queryMap = new HashMap();
			queryMap.put("orderId", orderId);
			//订单商品
			return this.list(this.getStatementName("selectAgentOrderItem"), queryMap);
			
		}catch(BusinessException e){
			throw e;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 订单追踪
	 * @param orderId
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Order> getOrderLog(@ErpOrders.AnnoOrderId String orderId){
		
		Map queryMap = new HashMap();
		queryMap.put("orderId", orderId);
		try {
			//订单追踪
			return this.list(this.getStatementName("selectOrderLog"), queryMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
     
	}
	
	/**
	 * 订单留言
	 * @param orderId
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<ErpOrderMessage> getOrderMessage(@ErpOrders.AnnoOrderId String orderId){
		
		Map queryMap = new HashMap();
		queryMap.put("orderId", orderId);
		try {
			//订单留言
			return this.list(this.getStatementName("selectOrderMessage"), queryMap);
//			return this.erpOrderMessageService.list(queryMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
     
	}
	

	/**
	 * 订单打印(推送)
	 */
	@Transactional
	public void pushOrderPrintByOrderId(@ErpOrders.AnnoOrderId String orderId){
		
		//基本验证
		if(StringUtils.isBlank(orderId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"订单号不能为空");
		}
		try{

			ErpOrders orders = this.erpOrdersService.one(orderId);
//			this.sendMessageService.pushMessageToTerminals(orders, "onlyPrintOrder", "0");

		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public JSONObject checkOrderAdd(String checkTime,String shopId){
		JSONObject jSONObject = new JSONObject();
		Map checkMap = new HashMap();
		checkMap.put("checkTime", checkTime);
		checkMap.put("shopId", shopId);
		Page page = new Page();
		page.setPageNumber(1);
		page.setPageSize(1);
		List<Order> orders =  this.list(this.getStatementName("checkOrderAdd"), checkMap,page);
		
		jSONObject.put("orderList", orders);
		
		return executeRerutn(jSONObject);
	}

	/**
	 * 设置打印类型
	 * @param printType
	 * @param shopId
	 * @return
	 */
	@Transactional
	public JSONObject setPrintType(String printType, String shopId) {
		if(StringUtils.isBlank(printType)){
			printType="3";
		}
		ErpShop erpShop = new ErpShop();
		erpShop.setShopId(shopId);
		erpShop.setPrintType(printType);
		this.erpShopService.update(erpShop);
		JSONObject jsonObject = new JSONObject();
		return this.executeRerutn(jsonObject );
	}
}
